import { segment } from "oicq"
import data from '../model/XiuxianData.js'
import config from "../model/Config.js"
import plugin from '../../../lib/plugins/plugin.js'
import fs from "node:fs";
import common from "../../../lib/common/common.js";

/**
 * 定时任务
 */
export class player_control extends plugin {
    constructor() {
        super({
            name: '人物控制',
            dsc: '控制人物的行为',
            event: 'message',
            priority: 300,
            rule: [
                {
                    reg: '^#出关$',
                    fnc: 'chuGuan'
                },
                {
                    reg: '^#结束打工$',
                    fnc: 'endWork'
                }
            ]
        });


    }

    /**
     * 人物结束闭关
     * @param e
     * @returns {Promise<void>}
     */
    async chuGuan(e) {
        let player_action = await this.getPlayerAction(e.user_id);
        let state = await this.getPlayerState(player_action);
        if (state == "空闲") {
            e.reply("当前人物状态空闲，不需要出关");
            return;
        }
        if (player_action.action != "闭关") {
            e.reply("当前人物并未在闭关");
            return ;
        }

        //结算
        let end_time = player_action.end_time;
        let start_time = player_action.end_time - player_action.time;
        let now_time = new Date().getTime();
        let time;
        if (end_time > now_time) {//属于提前结束
            time = parseInt((new Date().getTime() - start_time) / 1000 / 60);
        } else {//属于结束了未结算
            time = parseInt((player_action.time) / 1000 / 60);
        }
        if (e.isGroup) {
            await this.biguan_jiesuan(e.user_id, time, false, e.group_id);//提前闭关结束不会触发随机事件
        } else {
            await this.biguan_jiesuan(e.user_id, time, false);//提前闭关结束不会触发随机事件
        }
        let arr = player_action;
        arr.is_jiesuan = 1;
        arr.end_time = new Date().getTime();//结束的时间也修改为当前时间
        await redis.set("xiuxian:player:" + e.user_id + ":action", JSON.stringify(arr));

    }

    /**
     * 人物结束打工
     * @param e
     * @returns {Promise<void>}
     */
    async endWork(e) {
        let player_action = await this.getPlayerAction(e.user_id);
        let state = await this.getPlayerState(player_action);
        if (state == "空闲") {
            e.reply("当前人物状态空闲，不需要结束打工");
            return;
        }
        if (player_action.action != "打工") {
            e.reply("当前人物并未在打工");
            return ;
        }

        //结算
        let end_time = player_action.end_time;
        let start_time = player_action.end_time - player_action.time;
        let now_time = new Date().getTime();
        let time;
        if (end_time > now_time) {//属于提前结束
            time = parseInt((new Date().getTime() - start_time) / 1000 / 60);
        } else {//属于结束了未结算
            time = parseInt((player_action.time) / 1000 / 60);
        }
        if (e.isGroup) {
            await this.dagong_jiesuan(e.user_id, time, false, e.group_id);//提前闭关结束不会触发随机事件
        } else {
            await this.dagong_jiesuan(e.user_id, time, false);//提前闭关结束不会触发随机事件
        }

        let arr = player_action;
        arr.is_jiesuan = 1;
        arr.end_time = new Date().getTime();//结束的时间也修改为当前时间
        await redis.set("xiuxian:player:" + e.user_id + ":action", JSON.stringify(arr));

    }




    /**
     * 闭关结算
     * @param user_id
     * @param time持续时间(单位用分钟)
     * @param is_random是否触发随机事件  true,false
     * @param group_id  回复消息的地址，如果为空，则私聊
     * @returns {Promise<void>}
     */
     async  biguan_jiesuan(user_id, time, is_random, group_id){
        let player_data = data.getData("player", user_id);
        let Player_level_id = data.Level_list.find(item => item.level == player_data.境界).level_id
        let xiuwei = parseInt((50 + 3 * Player_level_id) * (player_data.修炼效率提升 + 1));//增加的修为
        let blood = parseInt(player_data.血量上限 * 0.02);//恢复的血量
        let other_xiuwei = 0;//额外修为
        let msg=[segment.at(user_id)];
        if (is_random) {//随机事件预留空间
            let rand = Math.random();
            if (rand < 0.2) {
                rand = Math.trunc(rand * 10) + 45;
                other_xiuwei = rand * time;
                msg.push("\n本次闭关顿悟,额外增加修为:" + rand * time);
            } else if (rand > 0.8) {
                rand = Math.trunc(rand * 10) + 5;
                other_xiuwei = -1 * rand * time;
                msg.push("\n由于你闭关时隔壁装修,导致你差点走火入魔,修为下降" + rand * time);
            }
        }
    
        //设置修为，设置血量
        await this.setFileValue(user_id, xiuwei * time + other_xiuwei, "修为");
        await this.setFileValue(user_id, blood * time, "当前血量");
    
        //给出消息提示
        if (is_random) {
            msg.push("\n闭关结束,增加修为:" + xiuwei * time, "  获得治疗,血量增加:" + blood * time);
        } else {
            msg.push("\n提前出关,增加修为:" + xiuwei * time, "  获得治疗,血量增加:" + blood * time);
        }
    
        if (group_id) {
            await this.pushInfo(group_id, true, msg)
        } else {
            await this.pushInfo(user_id, false, msg);
        }
        return;
    }
        /**
         * 打工结算
         * @param user_id
         * @param time持续时间(单位用分钟)
         * @param is_random是否触发随机事件  true,false
         * @param group_id  回复消息的地址，如果为空，则私聊
         * @returns {Promise<void>}
         */
     async  dagong_jiesuan(user_id, time, is_random, group_id){
        let player_data = data.getData("player", user_id);
        let Player_level_id = data.Level_list.find(item => item.level == player_data.境界).level_id;
        let lingshi = 45 + 3 * Player_level_id;
        let other_lingshi = 0;//额外的灵石
        let msg=[segment.at(user_id)];
        if (is_random) {//随机事件预留空间
            let rand = Math.random();
            if (rand < 0.2) {
                rand = Math.trunc(rand * 10) + 40;
                other_lingshi = rand * time;
                msg.push("\n本次打工获得小费:" + rand * time);
            } else if (rand > 0.8) {
                rand = Math.trunc(rand * 10) + 5;
                other_lingshi = -1 * rand * time;
                msg.push("\n由于你的疏忽,货物被人顺手牵羊,老板大发雷霆,灵石减少" + rand * time);
            }
        }
        let get_lingshi = lingshi * time + other_lingshi;//最后获取到的灵石
    
        //设置灵石
        await this.setFileValue(user_id, get_lingshi, "灵石");
    
        //给出消息提示
        if (is_random) {
            msg.push("\n打工结束,增加灵石:" + get_lingshi);
        } else {
            msg.push("\n提前打工结束,增加灵石:" + get_lingshi);
        }
        //区分群消息推送和私人消息推送
        if (group_id) {
            await this.pushInfo(group_id, true, msg)
        } else {
            await this.pushInfo(user_id, false, msg);
        }
        return;
    }


    /**
     * 获取缓存中的人物状态信息
     * @param user_id
     * @returns {Promise<void>}
     */
    async getPlayerAction(user_id) {
        let redis_data = await redis.get("xiuxian:player:" + user_id + ":action");
        let player_action = JSON.parse(redis_data);//转为json格式数据
        return player_action;
    }

    /**
     * 获取人物的状态，返回具体的状态或者空闲
     * @param player_action
     * @returns {Promise<void>}
     */
    async getPlayerState(player_action) {
        if (player_action == null) {
            return "空闲";
        }
        let now_time = new Date().getTime();
        let end_time = player_action.end_time;
        //当前时间>=结束时间，并且未结算 属于已经完成任务，却并没有结算的
        //当前时间<=完成时间，并且未结算 属于正在进行
        if (!((now_time >= end_time && player_action.is_jiesuan == 0) || (now_time <= end_time && player_action.is_jiesuan == 0))) {
            return "空闲";
        }
        return player_action.action;
    }


    /**
     * 推送消息，群消息推送群，或者推送私人
     * @param id
     * @param is_group
     * @returns {Promise<void>}
     */
    async pushInfo(id, is_group, msg) {
        if (is_group) {
            await Bot.pickGroup(id)
                .sendMsg(msg)
                .catch((err) => {
                    Bot.logger.mark(err);
                });
        } else {
            await common.relpyPrivate(id, msg);
        }
    }

    
    /**
     * 增加player文件某属性的值（在原本的基础上增加）
     * @param user_qq
     * @param num 属性的value
     * @param type 修改的属性
     * @returns {Promise<void>}
     */
    async setFileValue(user_qq, num, type) {
        let user_data = data.getData("player", user_qq);
        let current_num = user_data[type];//当前灵石数量
        let new_num = current_num + num;
        if (type == "当前血量" && new_num > user_data.血量上限) {
            new_num = user_data.血量上限;//治疗血量需要判读上限
        }
        user_data[type] = new_num;
        await data.setData("player", user_qq, user_data);
        return;
    }

}


/**
 * 判断对象是否不为undefined且不为null
 * @param obj 对象
 * @returns obj==null/undefined,return false,other return true
 */
function isNotNull(obj) {
    if (obj == undefined || obj == null)
        return false;
    return true;
}